package org.bling.star.server.service;

import org.bling.star.common.command.*;
import org.bling.star.common.model.StreamMessage;
import org.bling.star.common.model.UserInfo;
import org.bling.star.server.connect.GlobalPoolManager;
import org.bling.star.server.connect.StreamPool;
import org.bling.star.server.connect.node.InstanceConnection;
import org.bling.star.server.connect.node.TalkingStream;
import org.bling.star.server.mappers.StreamMessageMappers;
import org.bling.star.server.service.impl.StreamMessageService;
import org.mapstruct.factory.Mappers;
import org.slf4j.Logger;

import java.util.List;

public class ConnectDealServiceImpl implements ConnectDealService {
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(ConnectDealServiceImpl.class);
    private final StreamMessageMappers personMapper = Mappers.getMapper(StreamMessageMappers.class);
    private final StreamMessageService streamMessageService = new StreamMessageService();
    @Override
    public StreamMessage createTalkingPool(CreateCommand createCommand, InstanceConnection connect) {
        StreamMessage streamMessage = new StreamMessage();
        TalkingStream build = TalkingStream.build();
        System.out.println("createTalking");
        Boolean isConnected = build.connect(connect);
        Boolean aBoolean = connect.addStreamPool(build);
        log.info(aBoolean.toString());
        if(isConnected) {
            streamMessage = personMapper.toStreamMessage(build);
            List<UserInfo> userInfos = streamMessageService.roommateList(build);
            streamMessage.setUsers(userInfos);
        }
        return streamMessage;
    }

    @Override
    public Boolean join(JoinCommand joinCommand, InstanceConnection connect) {
        StreamPool from = GlobalPoolManager.getFrom(joinCommand.getSecretKey());
        Boolean join = from.connect(connect);
        connect.addStreamPool(from);
        if(join) {
            log.info("连接:{}已加入聊天室:{},",connect.getUserInfo(),this.toString());
        }
        return join;
    }

    @Override
    public Boolean talking(TalkingCommand talkingCommand, InstanceConnection connect) {
        StreamPool streamPool = connect.getStreamPool(talkingCommand.getSecretKey());
        Boolean broadcast = streamPool.broadcast(talkingCommand.getMessage(),connect);
        return broadcast;
    }

    @Override
    public Boolean exit(ExitCommand exitCommand, InstanceConnection connect) {
        StreamPool streamPool = connect.getStreamPool(exitCommand.getSecretKey());
        streamPool.remove(connect);
        connect.removeStreamPool(streamPool);
        return true;
    }

    @Override
    public Boolean disconnect(DisConnectCommand disconnectCommand, InstanceConnection connect) {
        return connect.close();
    }
}
